﻿using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;

public enum SkuType {
	Managed = 0,
	UnManaged 
};

public class IAPScript {

	/* Interface to native implementation */
	#if UNITY_IOS
	[DllImport ("__Internal")]
	private static extern void _SetGameObjectNameForIAP(string gameObjectName);

	[DllImport ("__Internal")]
	private static extern void _PurchaseById(string productId);

	[DllImport ("__Internal")]
	private static extern void _RestorePurchaseById(string productId);

	[DllImport ("__Internal")]
	private static extern void _RestoreAllPurchases();
	#endif

	public void SetGameObjectNameForIAP(string gameObjectName) 
	{
		// Call plugin only when running on real device
		if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android) {
			#if UNITY_ANDROID
			SSCIapAdapter.getInstance().setGameObjectName(gameObjectName);
			#elif UNITY_IOS
			_SetGameObjectNameForIAP(gameObjectName);
			#endif
		}
	}

	public void PurchaseById(string productId,SkuType skuType)
	{
		// Call plugin only when running on real device
		if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android) {
			#if UNITY_ANDROID
			string tmpType = skuType == SkuType.Managed ? "Managed":"Unmanaged";
			SSCIapAdapter.getInstance().purchase(productId,tmpType);
			#elif UNITY_IOS
			_PurchaseById(productId);
			#endif
		}
	}

	public void RestorePurchaseById(string productId)
	{
		// Call plugin only when running on real device
		if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android) {
			#if UNITY_ANDROID
			SSCIapAdapter.getInstance().restore();
			#elif UNITY_IOS
			_RestorePurchaseById(productId);
			#endif
		}

	}

	public void RestoreAllPurchases()
	{
		// Call plugin only when running on real device
		if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android) {
			#if UNITY_ANDROID
			SSCIapAdapter.getInstance().restore();
			#elif UNITY_IOS
			_RestoreAllPurchases();
			#endif
		}

	}
	/// <summary>
	/// only for android 
	/// 
	/// </summary>
	public void query()
	{
		// Call plugin only when running on real device
		if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android) {
			#if UNITY_ANDROID
			SSCIapAdapter.getInstance().query();
			#elif UNITY_IOS
			#endif
		}

	}
}
